package com.motherchild.user.service.impl;

import com.motherchild.admin.dto.ProductDTO;
import com.motherchild.admin.mapper.OrderMapper;
import com.motherchild.admin.mapper.ProductMapper;
import com.motherchild.admin.vo.ProductDetailVO;
import com.motherchild.user.dto.ShippingAddressDTO;
import com.motherchild.user.dto.User;
import com.motherchild.user.dto.UserOrderDTO;
import com.motherchild.user.dto.UserOrderItemDTO;
import com.motherchild.user.dto.UserOrderItemDTO;
import com.motherchild.user.mapper.ShippingAddressMapper;
import com.motherchild.user.mapper.UserOrderMapper;
import com.motherchild.user.service.UserOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author zhuchenxu
 * @create 2025-03-12-17:37
 */
@Service
public class UserOrderServiceImpl implements UserOrderService {
    @Autowired
    private UserOrderMapper orderMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ShippingAddressMapper shippingAddressMapper;
    @Override
    public void createOrder(UserOrderDTO orderDTO) {
        // 生成订单号
        String orderNo = generateOrderNo();
        orderDTO.setOrderNo(orderNo); // 设置订单号
        ShippingAddressDTO shippingAddressDTO = shippingAddressMapper.selectAddressById(orderDTO.getAddressId());
        orderDTO.setShippingName(shippingAddressDTO.getName());
        orderDTO.setShippingPhone(shippingAddressDTO.getPhone());
        orderDTO.setShippingAddress(shippingAddressDTO.getAddress());
        orderDTO.setStatus(10);
        // 插入订单
        orderMapper.insertOrder(orderDTO);

        // 插入订单详细项
        List<UserOrderItemDTO> items = orderDTO.getItems();
        for (UserOrderItemDTO item : items) {
            // 从产品表获取产品信息

            ProductDetailVO product = productMapper.selectAil(item.getProductId());
            if (product != null) {
                item.setProductName(product.getName());
                item.setProductImage(product.getMainImage());
                item.setUnitPrice(product.getPrice());
                // 计算总价
                BigDecimal quantity = new BigDecimal(item.getQuantity());
                BigDecimal totalPrice = quantity.multiply(product.getPrice());
                item.setTotalPrice(totalPrice);
                item.setUnitPrice(product.getPrice());
                item.setOrderNo(orderNo);
                item.setUserId(orderDTO.getUserId());
                orderMapper.insertOrderItem(item); // 插入订单项
                orderMapper.deleteOrder(orderDTO.getUserId(),item.getProductId() );
            }

        }


    }
    private String generateOrderNo() {
        return "1" + System.currentTimeMillis(); // 示例：使用当前时间戳生成订单号
    } 
}
    

